<template>
  <el-dialog
    title="定向发放详情"
    v-model="visible"
    width="800px"
    @close="onClose"
    :close-on-click-modal="false"
  >
    <div class="main">
      <el-form :model="queryParams" ref="queryRef" :inline="true">
        <el-form-item label="用户手机号" prop="mobile">
          <el-input
            style="width: 200px"
            v-model.trim="queryParams.mobile"
            placeholder="请输入"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="优惠券状态" prop="status">
          <!-- 1未发放2发放中3已发放4发放失败 -->
          <el-select v-model="queryParams.status" fit-input-width clearable placeholder="请选择">
            <el-option
              v-for="item in STATUS_OPTIONS"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" @click="handleAdd"> 批量新增 </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" @click="handleBatchDistribute"> 批量发放 </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" @click="handleBatchDelete"> 一键删除 </el-button>
        </el-col>
      </el-row>
      <el-table v-loading="loading" size="default" index :data="dataList">
        <el-table-column label="用户手机号" align="center" prop="mobile" />
        <el-table-column label="状态" align="center" prop="status">
          <template #default="{ row }">
            <span>{{ getStatusValue(row.status) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="是否小程序用户" align="center" prop="isClient">
          <template #default="{ row }">
            <span>{{ row.isClient === 1 ? '是' : '否' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="发券时间" width="200" align="center" prop="sendTime" />
        <el-table-column label="操作" align="center" prop="name">
          <template #default="{ row }">
            <!-- 已发放和发放失败不可以删除 -->
            <div v-if="row.status !== 3 && row.status !== 4">
              <el-link
                style="margin-left: 6px"
                :underline="false"
                type="primary"
                @click="handleDelete(row.id)"
                >删除</el-link
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-right: 10px">
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </div>
    <!-- 批量新增 -->
    <directionalAdd ref="addRef" @close="getList" />
  </el-dialog>
</template>

<script setup>
import {
  deletAllApi,
  deleteDirectionalApi,
  directionalGrantApi,
  expireCouponApi,
  getDirectionalListApi
} from '@/api/marketing/activity'
import directionalAdd from './directionalAdd.vue'
const queryRef = ref(null)
const props = defineProps({
  validStartTime: {
    type: String,
    default: ''
  }
})

const emits = defineEmits(['refresh'])

const total = ref(0)
const dataList = ref([])
const visible = ref(false)

const queryParams = reactive({
  couponId: '',
  mobile: '',
  status: '',
  pageNum: 1,
  pageSize: 10
})
const loading = ref(true)

// 删除
function handleDelete(id) {
  deleteDirectionalApi({ id }).then((res) => {
    getList()
  })
  // ElMessageBox.confirm('该券将会被强制失效', '操作', {
  //   confirmButtonText: '确定',
  //   cancelButtonText: '取消',
  //   type: 'error'
  // })
  //   .then(() => {
  //     expireCouponApi({ checkId: id }).then(() => {
  //       ElMessage({
  //         type: 'success',
  //         message: '操作成功'
  //       })
  //       handleQuery()
  //     })
  //   })
  //   .catch(() => {})
}
/**批量删除 */
function handleBatchDelete() {
  ElMessageBox.confirm('是否删除未发放和待发放的用户数据', '', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deletAllApi(queryParams.couponId)
      .then(() => {
        ElMessage({
          type: 'success',
          message: `操作成功`
        })
      })
      .finally(() => {
        getList()
      })
  })
}
/** 查询用户列表 */
function getList() {
  loading.value = true
  getDirectionalListApi(queryParams)
    .then((res) => {
      loading.value = false
      dataList.value = res?.data?.rows || []
      total.value = res?.data?.total || 0
    })
    .catch(() => {
      loading.value = false
      dataList.value = []
      total.value = 0
    })
}

// TODO:新增已禁用
const STATUS_OPTIONS = [
  {
    label: '全部状态',
    value: ''
  },
  {
    label: '未发放',
    value: 1
  },
  {
    label: '发放中',
    value: 2
  },
  {
    label: '已发放',
    value: 3
  },
  {
    label: '发放失败',
    value: 4
  }
]
const getStatusValue = computed(() => {
  return (status) => {
    return STATUS_OPTIONS.find((item) => item.value === status)?.label
  }
})

// 搜索
function handleQuery() {
  queryParams.pageNum = 1
  console.log('queryParams', queryParams)
  getList()
}

// 重置
function resetQuery() {
  queryRef.value.resetFields()
  handleQuery()
}

// 批量发放
function handleBatchDistribute() {
  ElMessageBox.confirm('是否一键发放', '操作', {
    confirmButtonText: '发放',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      directionalGrantApi({ couponId: queryParams.couponId })
        .then((res) => {
          if (res?.data !== null) {
            ElMessage({
              type: 'success',
              message: `已发送${res?.data}张优惠券`
            })
          } else if (res?.data === null && res?.msg) {
            ElMessage({
              type: 'error',
              message: `${res?.msg}`
            })
          }
          getList()
        })
        .catch((err) => {
          ElMessage({
            type: 'error',
            message: err?.msg || '发放失败'
          })
        })
    })
    .catch(() => {})
}

// 批量新增
const addRef = ref(null)
function handleAdd() {
  console.log('queryParams.couponId', queryParams.couponId)
  addRef.value.init(queryParams.couponId)
}

function onClose() {
  queryRef.value.resetFields()
  queryParams.pageNum = 1
  emits('refresh')
}

function init(id) {
  visible.value = true
  queryParams.couponId = id
  getList()
}

defineExpose({
  init
})
</script>

<style lang="scss" scoped>
:deep(.pagination-container .el-pagination) {
  right: 20px;
}
.main {
  position: relative;
  transform: translate3d(0, -30px, 0);
}
.type {
  margin-bottom: 20px;
}
</style>
